<script lang="ts" setup>
onActivated(async () => {
  await getmovieInfo()
})

const tabIndex = ref(0)
const filmIndex = ref(0)
const showPlayApp = ref(false)
const showWatchApp = ref(false)
const showLoginPopup = ref(false)
const router = useRouter()
const route = useRoute()
const { userInfo } = toRefs(useUserStore())
const { sourceCdnUrl } = useRuntimeConfig().public
const movieInfo = ref<any>({
  episodes: 0,
})

async function getmovieInfo() {
  const { query } = useRoute()
  if (query?.fid) {
    const fid = Number(useRequest.decrypt(query.fid, 'fZ9&N6ufs4gACs@a'))
    const { Data } = await useRequest.post('GetFilmDetail', { id: fid })
    movieInfo.value = Data ?? {}
  }
}

const tabList = computed(() => {
  const tabCount = Math.ceil(movieInfo.value?.episodes / 50)
  return Array(tabCount)
    .fill('')
    .map((_, index) => {
      const start = index * 49 + 1
      const end =
        (index + 1) * 49 < movieInfo.value?.episodes ? (index + 1) * 49 : movieInfo.value.episodes
      return `${start}-${end}`
    })
})

const movieList = computed(() => {
  const start = tabIndex.value * 49 + 1
  const end =
    (tabIndex.value + 1) * 49 < movieInfo.value.episodes
      ? (tabIndex.value + 1) * 49
      : movieInfo.value.episodes
  const mvList = []
  for (let i = start; i <= end; i++) {
    mvList.push(i)
  }
  return mvList
})

async function handleMovieItem(no: number, index: number) {
  filmIndex.value = index
  movieInfo.value.curEpisode = no
  if (no > 10) {
    showPlayApp.value = true
  } else {
    const locked = !movieInfo.value?.unlocked_film_episodes?.some(
      (noItem: any) => no === noItem.episode_no,
    )

    if (locked) {
      const { Data } = await useRequest.post('/UnlockFilmEpisode', {
        episodes: no,
        film_id: movieInfo.value.id,
        get_price: 1,
      })
      Object.assign(movieInfo.value, {
        episodeInfo: {
          coins: Data?.price,
        },
      })
      // 没有登录先登录
      if (!userInfo.value?.user_id) {
        showLoginPopup.value = true
      } else {
        showWatchApp.value = true
      }
    } else {
      router.push({
        path: '/player',
        query: {
          fid: useRequest.encrypt(String(movieInfo.value.id)),
          epid: no,
        },
      })
    }
  }
}

// 手动解锁成功
function onManualUnlock() {
  getmovieInfo()
}
</script>

<template>
  <div class="page">
    <!-- nav-bar -->
    <NavBar
      :show-back="true"
      :show-nav-right="false">
    </NavBar>

    <div class="page-container">
      <!-- movie-info -->
      <div class="movie-info">
        <img
          :key="movieInfo?.image"
          v-lazy="{ src: `${sourceCdnUrl}${movieInfo?.image ?? ''}`, preLoad: 1.3, attempt: 1 }"
          class="img" />

        <div class="info">
          <h1 class="title">{{ movieInfo.name }}</h1>
          <div class="date">Total {{ movieInfo.episodes }} Eplsodes</div>
          <div class="language">Language：{{ movieInfo.language }}</div>
          <div class="tag-list">
            <div
              v-for="tag in movieInfo?.keywords"
              :key="tag"
              class="tag-item">
              {{ tag }}
            </div>
          </div>
        </div>
      </div>
      <div class="desc">
        <h2 class="desc-tl">Introduction</h2>
        <article>
          <van-text-ellipsis
            :rows="3"
            :content="movieInfo.description"
            expand-text=" fewer"
            collapse-text=" more" />
        </article>
      </div>
      <div class="movie-wrap">
        <div class="tab-list">
          <div
            v-for="(item, index) in tabList"
            :key="item"
            class="tab-item"
            :class="{ 'is-active': tabIndex === index }"
            @click="tabIndex = index">
            {{ item }}
          </div>
        </div>
        <div class="movie-list">
          <div
            v-for="(item, itIndex) in movieList"
            :key="item"
            class="movie-item"
            :class="{ 'is-active': Number(route.query.epid) === item }"
            @click="handleMovieItem(item, itIndex)">
            <svg-icon
              v-if="
                !movieInfo?.unlocked_film_episodes?.some(
                  (noItem: any) => item === noItem.episode_no,
                )
              "
              name="lock"
              class="lock-icon">
            </svg-icon>
            <svg-icon
              v-if="Number(route.query.epid) === item"
              name="onplay"
              class="onplay-icon">
            </svg-icon>
            <span>{{ item }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- lock-popup -->
    <van-popup
      v-model:show="showWatchApp"
      teleport="body">
      <LazyWatchPopup
        :film-info="movieInfo"
        @close="showWatchApp = false"
        @unlocked="onManualUnlock">
      </LazyWatchPopup>
    </van-popup>

    <!-- login-popup -->
    <van-popup
      v-model:show="showLoginPopup"
      teleport="body">
      <LazyLoginPopup @close="showLoginPopup = false"></LazyLoginPopup>
    </van-popup>

    <!-- login-popup -->
    <van-popup
      v-model:show="showPlayApp"
      teleport="body">
      <LazyPlayPopup @close="showPlayApp = false"></LazyPlayPopup>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.page {
  height: 100%;
  overflow-y: auto;
  padding: 50px 14px 14px;
  .page-container {
    .movie-info {
      @include flexbox();
      margin-bottom: 20px;
      .img {
        width: 98px;
        height: 135px;
        margin-right: 14px;
      }
      .info {
        .title {
          font-size: 15px;
          font-weight: 800;
          margin-bottom: 14px;
        }
        .date,
        .language {
          font-size: 12px;
          color: #d3d2d7;
          margin-bottom: 14px;
        }
        .tag-list {
          @include flexbox($fw: wrap);
          .tag-item {
            @include flexbox($jc: center, $ai: center);
            height: 24px;
            padding: 0 8px;
            margin-right: 6px;
            border-radius: 22px;
            background: #21202f;
            font-size: 11px;
            min-width: 36px;
            margin-bottom: 6px;
            &:nth-child(4n) {
              margin-right: 0;
            }
          }
        }
      }
    }
    .desc {
      margin-bottom: 24px;
      .desc-tl {
        font-size: 15px;
        font-weight: 800;
        margin-bottom: 18px;
      }
      article {
        p {
          font-size: 13px;
          line-height: 24px;
          color: #d3d2d7;
        }
      }
    }
    .movie-wrap {
      .tab-list {
        margin-bottom: 8px;
        @include flexbox();
        .tab-item {
          margin-right: 20px;
          cursor: pointer;
          &.is-active {
            color: $primary-color;
          }
        }
      }
      .movie-list {
        @include flexbox($fw: wrap);
        .movie-item {
          position: relative;
          width: calc((100vw - 82px) / 7);
          height: calc((100vw - 82px) / 7);
          line-height: 42px;
          text-align: center;
          flex-shrink: 0;
          border-radius: 4px;
          background: #21202f;
          margin-bottom: 9px;
          margin-right: 9px;
          cursor: pointer;
          &:nth-child(7n) {
            margin-right: 0;
          }
          .lock-icon {
            position: absolute;
            top: 3px;
            right: 3px;
            font-size: 10px;
          }
          .onplay-icon {
            position: absolute;
            left: 3px;
            bottom: 3px;
            font-size: 10px;
          }
          &.is-active {
            background-color: rgba(249, 57, 68, 0.2);
          }
        }
      }
      @media (min-width: 500px) and (min-height: 640px) {
        .movie-item {
          width: calc((100% - 72px) / 7) !important;
          height: calc((100% - 72px) / 7) !important;
        }
      }
    }
  }
}
</style>
